<script setup>
import { ref, nextTick } from 'vue'
import api from '@/api'
import uploadFile from '@/components/uploadFile.vue'
import Player from 'xgplayer'
import { transformDuration } from '@/utils'
import { Modal } from '@arco-design/web-vue'
import uploadImage from '@/components/uploadImage.vue'

const emit = defineEmits(['close'])

const listFormData = ref({
  page: 1,
  keyword: '',
})
const listLoading = ref(false)
const listTotal = ref(0)
const listData = ref([
  {
    id: 1,
    name: '第一节',
  },
])
const getListData = async (page = 1) => {
  listLoading.value = true
  try {
    listFormData.value.page = page
    const res = await api.get(`courses/${course.value.id}/sections`, {
      params: listFormData.value,
    })
    listData.value = res.data
    listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

const course = ref(null)
const visible = ref(false)

const show = (item) => {
  course.value = item
  formData.value.course_id = item.id
  visible.value = true
  getListData()
}

defineExpose({ show })

const formRef = ref()
const formVisible = ref()
const formItem = ref()
const formLoading = ref()
const formData = ref({
  course_id: '',
  name: '',
  duration: '',
  video_url: '',
  image_url: '',
})
const formRules = {
  name: [
    {
      required: true,
      message: '请填写课程名称',
    },
  ],
  duration: [
    {
      required: true,
      message: '请填写视频时长',
    },
  ],
  video_url: [
    {
      required: true,
      message: '请上传视频',
    },
  ],
  image_url: [
    {
      required: true,
      message: '请上传视频封面',
    },
  ],
}
const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }

  formLoading.value = true

  try {
    if (formItem.value) {
      await api.put('sections/' + formItem.value.id, formData.value)
    } else {
      await api.post('sections', formData.value)
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }

  formLoading.value = false

  return false
}
const create = () => {
  formRef.value?.resetFields()
  formData.value.image_url = ''
  formItem.value = null
  formVisible.value = true
}

const update = (item) => {
  formRef.value?.resetFields()
  formItem.value = item
  formData.value.name = item.name
  formData.value.duration = transformDuration(item.duration, true)
  formData.value.video_url = item.video_url
  formData.value.image_url = item.image_url
  formVisible.value = true

  changeVideo(item.video_url)
}

const del = (item) => {
  Modal.confirm({
    title: '删除',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete('sections/' + item.id)

      getListData()
    },
  })
}

const playerRef = ref()
let player = null
const changeVideo = (video_url) => {
  nextTick(() => {
    if (player) {
      player.src = video_url
    } else {
      player = new Player({
        el: playerRef.value,
        url: video_url,
        width: '100%',
        lang: 'zh-cn',
      })
    }
  })
}

const onClose = () => {
  if (player) {
    player.destroy()
    player = null
  }
}
</script>

<template>
  <a-modal
    v-model:visible="visible"
    title="章节管理"
    :footer="false"
    body-style="padding:0"
    width="1000px"
    @before-close="emit('close')"
  >
    <div class="header">
      <a-space>
        <a-button type="primary" @click="create">添加章节</a-button>
      </a-space>
    </div>
    <a-table
      :loading="listLoading"
      @page-change="getListData"
      class="table"
      :data="listData"
      :pagination="{
        simple: true,
        showTotal: true,
        size: 'small',
        total: listTotal,
        pageSize: 30,
        current: listFormData.page,
      }"
    >
      <template #columns>
        <a-table-column
          title="章节"
          data-index="order"
          :width="60"
        ></a-table-column>
        <a-table-column title="封面" :width="200">
          <template #cell="{ record }">
            <img class="cell-img" :src="record.image_url" />
          </template>
        </a-table-column>
        <a-table-column title="标题" data-index="name"></a-table-column>
        <a-table-column title="时长">
          <template #cell="{ record }">
            {{ transformDuration(record.duration) }}
          </template>
        </a-table-column>
        <a-table-column align="right" :width="88">
          <template #cell="{ record }">
            <a-space>
              <a-button type="primary" size="mini" @click="update(record)">
                编辑
              </a-button>
              <a-button
                type="primary"
                status="danger"
                size="mini"
                @click="del(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>

  <a-modal
    v-model:visible="formVisible"
    :title="(formItem ? '编辑' : '添加') + '章节'"
    :ok-loading="formLoading"
    :on-before-ok="formSubmit"
    @close="onClose"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules">
      <a-form-item
        field="image"
        label="封面"
        help="请上传jpg、png、gif格式图片、文件大小不能超过1MB"
        validate-trigger="input"
      >
        <uploadImage
          v-model="formData.image_url"
          width="100%"
          height="300px"
        ></uploadImage>
      </a-form-item>

      <a-form-item field="name" label="标题">
        <a-input v-model="formData.name" allow-clear />
      </a-form-item>
      <a-form-item
        field="video_url"
        label="视频"
        help="请上传mp4格式视频、文件大小不能超过200MB"
        validate-trigger="input"
      >
        <div style="width: 100%">
          <div
            v-if="formData.video_url"
            ref="playerRef"
            style="margin-bottom: 10px"
          ></div>

          <uploadFile
            :accepts="['video/mp4']"
            v-model="formData.video_url"
            dir="videos"
            :maxSize="100"
            @change="changeVideo"
          ></uploadFile>
        </div>
      </a-form-item>

      <a-form-item field="duration" label="时长">
        <a-time-picker
          v-model="formData.duration"
          disableConfirm
          placeholder=""
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<style lang="scss" scoped>
.header {
  padding: 10px;
}

.cell-img {
  display: block;
  width: 200px;
}
</style>
